package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"


	"orchestrator/internal/infra/database/flex/po"
	"orchestrator/internal/infra/filter"
	jrpc "orchestrator/internal/infra/jsonrpc"
)

func transactionTest(ctx context.Context, c *jrpc.Jclient, b []byte) error {

	m := po.NewTBatchModel(c)

	tx, err := begin(ctx, c)
	if err != nil {
		return err
	}

	m.WithSession(tx)

	id := "1"
	r, err := m.FindOne(ctx, id)
	if err != nil {
		err := rollback(ctx, c, tx)
		if errors.Is(po.ErrNotFound, err) {
			return err
		}
		return err
	}

	err = commit(ctx, c, tx)
	if err != nil {
		return err
	}

	fmt.Printf("%+v\n", r)

	return err
}

func begin(ctx context.Context, c *jrpc.Jclient) (int, error) {

	var id int64
	r, err := c.Call(ctx, "transaction.begin")
	if err != nil {
		return 0, err
	}

	id, err = r.GetInt()
	if err != nil {
		return 0, err
	}

	return int(id), err

}

func commit(ctx context.Context, c *jrpc.Jclient, tx int) error {
	_, err := c.Call(ctx, "transaction.commit", tx)
	if err != nil {
		return err
	}
	return err
}

func rollback(ctx context.Context, c *jrpc.Jclient, tx int) error {
	_, err := c.Call(ctx, "transaction.rollback", tx)
	if err != nil {
		return err
	}
	return err
}



{{.impls}}
